package sol.cc;

import def.ListNode;
import utils.LinkedListUtils;

import java.util.List;

/**
 * 输入一个链表，输出该链表中倒数第k个结点。
 */
public class Issue2_2 {
    public static ListNode FindKthToTail(ListNode head, int k) {
        if (head == null)
            return null;

        int cnt = 0;
        ListNode ptr = head;
        while (ptr != null) {
            cnt++;
            ptr = ptr.next;
        }
        ptr = head;
        while (cnt > 0 && k != cnt) {
            cnt--;
            ptr = ptr.next;
        }
        if (cnt <= 0)
            return null;
        return ptr;
    }

    public static void main(String[] args) {
        ListNode head = LinkedListUtils.create(1, 2, 3, 4);
        int k = 1;
        ListNode ptr = FindKthToTail(head, k);
        System.out.println(ptr.val);
    }
}
